﻿using HelloMinasan.Web.Song.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using HelloMinasan.Business;
using HelloMinasan.Domain;
using HelloMinasan.Framework.Web;
using HelloMinasan.Resources;
using HelloMinasan.UserDefinedType;
using HelloMinasan.Framework.Web.WebHelpers;
using HelloMinasan.Business.Extend;

namespace HelloMinasan.Web.Song.Controllers
{
    public class SongController : ApplicationController
    {
        //private readonly IRepository._SongIRepository _songIRepository;
        ////private readonly IRepository._SongQuestionIRepository _songQuestionIRepository;
        //private readonly IRepository._FavouriteSongRepository _favouriteSongsIRepository;
        //private readonly IRepository._UserIRepository _userIRepository;
        //public SongController()
        //    : this(new SongRepository(), new FavouriteSongRepository(), new UserIRepository())
        //{
        //}

        //private SongController(
        //    IRepository._SongIRepository songRepository,
        //    IRepository._FavouriteSongRepository favouriteSongRepository,
        //    IRepository._UserIRepository userRepository)
        //{
        //    this._songIRepository = songRepository;
        //    this._userIRepository = userRepository;
        //    this._favouriteSongsIRepository = favouriteSongRepository;
        //}

        private ISongService songService;
        private IUserService userService;

        public SongController(ISongService songService, IUserService userService)
        {
            this.songService = songService;
            this.userService = userService;
        }

        // GET: /Song/
        //[AllowAnonymous]
        [HttpGet]
        public ActionResult Songs(int? id)
        {
            if (id != null)
            {
                HelloMinasan.Domain.Song song = songService.GetSongContent(id.Value, true);
                if (song == null)
                {
                    return View("AllSongs", songService.GetAllSongs());
                }
                if (song.IsLocked)
                {
                    return Redirect("/Home/Index");
                }
                return View(new SongViewModels()
                {
                    Song = songService.GetSongContent(id.Value, true),
                    Owners = song.User.Username,
                    SongName = song.SongName,
                    Singer = song.Singer,
                    Composer = song.Composer,
                    SongId = song.Id
                });
            }
            else
                return View("AllSongs", songService.GetAllSongs());
        }

        [Authorize]
        [HttpPost]
        public ActionResult Songs(SongViewModels model, int SongId)
        {
            HelloMinasan.Domain.Song song = songService.GetSongContent(SongId);

            if (song == null)
            {
                return View("AllSongs", songService.GetAllSongs());
            }
            //User user = new UserIRepository().FindUserById(User.Identity.Name);
            User user = userService.Get(CurrentUser.Id);
            if (user == null && (user.Id != song.Id || User.Identity.Name.ToLower() != "admin"))
            {
                return View("AllSongs", songService.GetAllSongs());
            }

            song.SongName = model.SongName;
            song.Singer = model.Singer;
            song.Composer = model.Composer;
            songService.EditSong(song);

            return View(new SongViewModels()
            {
                Song = songService.GetSongContent(SongId, true),
                Owners = song.User.Username,
                SongName = song.SongName,
                Singer = song.Singer,
                Composer = song.Composer
            });

        }

        public ActionResult AllSongs(int userId)
        {
            if (userId == 0)
            {
                return Redirect(Url.Content("~/Home"));
            }
            //if (new UserIRepository().FindUserById(id) != null)
            if (userService.Get(userId) != null)
            {
                var model = songService.GetSongsByUsername(userId);
                ViewBag.UserId = userId;
                return View(model);
            }
            else
            {
                return Redirect(Url.Action("Error", "Home"));
            }
        }
        [Authorize]
        [HttpGet]
        public ActionResult EditSong(int? id)
        {
            if (id != null)
            {
                try
                {
                    var obj = songService.GetSongContent(id.Value);
                    var model = new SongViewModels
                    {
                        SongId = obj.Id,
                        SongName = obj.SongName,
                        PostedDate = obj.PostedDate,
                        Images = obj.Images,
                        Grammar = obj.Grammar,
                        Singer = obj.Singer,
                        Composer = obj.Composer,
                        IsEdit = true
                    };
                    var lyricMain = obj.LyricDetails.Where(x => x.LyricStatus == true && x.Song.Id == id.Value).FirstOrDefault();
                    if (obj.IsEmbed)
                    {
                        model.SongURL = obj.SongURL;
                    }
                    else
                    {
                        model.URL = Path.Combine(Url.Content("~/Content/Upload/Musics"), obj.SongURL);
                    }

                    return View(model);
                }
                catch
                {
                    return Redirect(Url.Action("Error", "Home"));
                }
            }
            else
                return View("AllSongs", songService.GetAllSongs());
        }

        [ValidateInput(false)]
        [HttpPost]
        [Authorize]
        public ActionResult EditSong(SongViewModels model)
        {
            if (ModelState.IsValid)
            {
                bool checkImage = model.ImageFile == null && string.IsNullOrEmpty(model.Images);
                bool checkAudio = model.SongFile == null
                    && string.IsNullOrEmpty(model.SongURL)
                    && string.IsNullOrEmpty(model.URL);
                string err = string.Empty;
                err = checkImage ? Resource.Song_ImageNotSelect : string.Empty;
                err += checkAudio ? Resource.Song_AudioNotSelect : string.Empty;
                err += !Request.IsAuthenticated ? Resource.Song_RequiredAuthentication : string.Empty;

                if (model.SongFile != null && !ValidateFile.ListAudioExtentsion.Contains(
                    model.SongFile.FileName.Substring(
                    model.SongFile.FileName.Length - 3, 3)))
                {
                    err += Resource.Song_IncorrectAudioType;
                }
                if (model.ImageFile != null && !ValidateFile.ListImageExtentsion.Contains(
                    model.ImageFile.FileName.Substring(
                    model.ImageFile.FileName.Length - 3, 3)))
                {
                    err += Resource.Song_IncorrectImageType;
                }

                ViewBag.Error = err;
                if (Request.IsAuthenticated)
                {
                    try
                    {
                        HelperContent helper = new HelperContent();
                        model.Images = checkImage ? model.Images : checkSelection(model.Images, string.Empty, true, model.ImageFile, ref model);
                        model.SongURL = checkAudio ? model.SongURL : checkSelection(model.URL, model.SongURL, false, model.SongFile, ref model);

                        HelloMinasan.Domain.Song songObject = songService.Get(model.SongId);
                        if (songObject == null)
                        {
                            songObject = new HelloMinasan.Domain.Song()
                            {
                                SongName = model.SongName,
                                SongURL = model.SongURL,
                                Images = model.Images,
                                Singer = model.Singer,
                                Composer = model.Composer,
                                IsEmbed = model.IsEmbed,
                                Grammar = model.Grammar
                            };
                        }

                        songService.EditSong(songObject);
                        return Redirect(Url.Action("Songs", "Song", new { id = model.SongId }));
                    }
                    catch
                    {
                        //TO DO
                        ViewBag.Error = string.Format(Resource.Song_AddError, model.SongName);
                    }
                }
            }
            return View(model);
        }
        [Authorize]
        [HttpPost]
        public ActionResult DeleteSong(int id)
        {
            ResultObject result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    HelloMinasan.Domain.Song song = songService.GetSongContent(id);
                    //User user = new UserIRepository().FindUserById(User.Identity.Name);
                    User user = userService.Get(CurrentUser.Id);
                    if (user.Id == song.User.Id || user.Username.ToLower() == "admin")
                    {
                        songService.DeleteSong(id);
                        result.Result = true;
                        result.Message = Resource.Song_SuccessfullyEvent;
                        result.ReturnObject = Url.Action("Index", "Home");
                    }
                    else
                    {
                        result.Result = false;
                        result.Message = Resource.Song_OwnerRequest;
                    }
                }
                catch
                {
                    result.Result = false;
                    result.Message = Resource.Song_DeleteError;
                }
            }
            else
            {
                result.Result = false;
                result.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(result);
        }
        [Authorize]
        [HttpGet]
        public ActionResult AddSong()
        {
            var languageList = songService.GetLanguage(true);
            return View(new SongViewModels());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddSong(SongViewModels model)
        {
            if (ModelState.IsValid)
            {
                bool checkImage = model.ImageFile == null && string.IsNullOrEmpty(model.Images);
                bool checkAudio = model.SongFile == null
                    && string.IsNullOrEmpty(model.SongURL)
                    && string.IsNullOrEmpty(model.URL);
                string err = string.Empty;

                err = checkImage ? Resource.Song_ImageNotSelect : string.Empty;
                err += checkAudio ? Resource.Song_AudioNotSelect : string.Empty;
                err += !Request.IsAuthenticated ? Resource.Song_RequiredAuthentication : string.Empty;
                if (model.SongFile != null && !ValidateFile.ListAudioExtentsion.Contains(
                    model.SongFile.FileName.Substring(
                    model.SongFile.FileName.Length - 3, 3)))
                {
                    err += Resource.Song_IncorrectAudioType;
                }
                if (model.ImageFile != null && !ValidateFile.ListImageExtentsion.Contains(
                    model.ImageFile.FileName.Substring(
                    model.ImageFile.FileName.Length - 3, 3)))
                {
                    err += Resource.Song_IncorrectImageType;
                }

                ViewBag.Error = err;
                if (!checkImage && !checkAudio && Request.IsAuthenticated)
                {
                    try
                    {
                        HelperContent helper = new HelperContent();
                        model.Images = checkSelection(model.Images, string.Empty, true, model.ImageFile, ref model);
                        model.SongURL = checkSelection(model.URL, model.SongURL, false, model.SongFile, ref model);
                        HelloMinasan.Domain.Song songObject = new HelloMinasan.Domain.Song()
                        {
                            SongName = model.SongName,
                            SongURL = model.SongURL,
                            Images = model.Images,
                            //TO DO here
                            //Owners = new UserIRepository().FindUserById(User.Identity.Name).UserId,
                            User = userService.Get(CurrentUser.Id),
                            IsLocked = false,
                            PostedDate = DateTime.Now,
                            LikeTime = 0,
                            TypeSong = songService.GetTypeSong(1),
                            Singer = model.Singer,
                            Composer = model.Composer,
                            SongStatus = false,
                            IsEmbed = model.IsEmbed,
                            Grammar = model.Grammar,
                            CanUpdateGrammar = model.CanUpdateGrammar,
                            Liker = string.Empty,
                            LyricDetails = null
                        };
                        
                        //songId = songService.AddSong(songObject);

                        songObject.LyricDetails = new List<LyricDetail>()
                            {
                                //TO DO here
                                new LyricDetail()
                                {
                                    //LanguageId = int.Parse(model.SelectedLanguage),
                                    Language = userService.GetLanguage(int.Parse(model.SelectedLanguage)),
                                    //SongId = model.SongId,
                                    Song = songObject,
                                    LyricContent = model.OrginalLyric,
                                    //UpdateUser = CurrentUser.Id,//new UserIRepository().FindUserById(User.Identity.Name).UserId,
                                    User = userService.Get(CurrentUser.Id),
                                    LastUpdate = DateTime.Now,
                                    CanUpdate = model.CanUpdateLyric,
                                    IsOrginal = true
                                }
                            };

                        int songId = songService.AddSong(songObject);
                        return Redirect(Url.Action("MySong", "UserManagement", new { id = User.Identity.Name }));
                    }
                    catch (Exception ex)
                    {
                        //TO DO
                        ViewBag.Error = string.Format(Resource.Song_AddError, model.SongName);
                    }
                }
            }
            return View(model);
        }

        private string checkSelection(string priority1, string priority2, bool isImage, HttpPostedFileBase priority3, ref SongViewModels model)
        {
            string path = string.Empty;
            var resultCheck = UploadType.ByLocalFile;
            if (!string.IsNullOrEmpty(priority1)) resultCheck = UploadType.ByURL;
            else
                if (!string.IsNullOrEmpty(priority2)) resultCheck = UploadType.ByEmbed;
            switch (resultCheck)
            {
                case UploadType.ByURL:
                    path = priority1;
                    model.IsEmbed = false;
                    break;
                case UploadType.ByEmbed:
                    path = priority2;
                    model.IsEmbed = true;
                    break;
                case UploadType.ByLocalFile:
                    HelperContent helper = new HelperContent();
                    path = helper.NewID() + Path.GetExtension(priority3.FileName);
                    var str =
                        isImage ?
                        Path.Combine(Server.MapPath("~/Content/Upload/Images"), path) :
                        Path.Combine(Server.MapPath("~/Content/Upload/Musics"), path);
                    priority3.SaveAs(str);
                    model.IsEmbed = false;
                    if (isImage)
                    {
                        path = Url.Content("~/Content/Upload/Images/" + path);
                    }
                    else
                    {
                        path = Url.Content("~/Content/Upload/Musics/" + path);
                    }
                    break;
            }
            return path;
        }

        [HttpPost]
        public PartialViewResult RelativeSongs(SongViewModels model)
        {
            return PartialView();
        }

        [HttpGet]
        public ActionResult DoTest(int id)
        {
            var song = songService.GetSongContent(id);
            TestEntrie entry = new TestEntrie();
            if (song.QuestionQuizs.Any())
            {
                entry.Song = song;
                entry.Questions = new JavaScriptSerializer().
                    Deserialize<List<Question>>(song.QuestionQuizs.Where(x => x.Id == int.Parse(Request.QueryString["testId"])).First().QuizContent);
                entry.SongId = id;
            }
            return PartialView(entry);
        }

        [HttpPost]
        public ActionResult DoTest(TestEntrie model)
        {
            var song = songService.GetSongContent(model.SongId);
            List<Question> orginalQuestions = new JavaScriptSerializer().Deserialize<List<Question>>(song.QuestionQuizs.First().QuizContent);
            int totalQuestion = orginalQuestions.Count();
            int correctQuestion = 0;
            int score = 0;
            for (int i = 0; i < orginalQuestions.Count(); i++)
            {
                if (orginalQuestions[i].CorrectAnswer == model.Questions[i].SelectedAnswer)
                {
                    correctQuestion++;
                    score++;
                }
            }
            TestResult testResult = new TestResult()
            {
                Score = score,
                SongId = model.SongId,
                Total = totalQuestion,
                Correct = correctQuestion,
                CorrectPercent = (correctQuestion * 100 / totalQuestion)
            };
            model.Result = testResult;
            model.Song = song;
            if (Request.IsAuthenticated)
            {
                songService.UpdateScore(CurrentUser.Id, score);
            }
            return PartialView(model);
        }

        [Authorize]
        [HttpGet]
        public ActionResult ResultTest()
        {
            return View();
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpGet]
        public ActionResult EditGrammar(int id)
        {
            var obj = songService.GetSongContent(id);
            if (obj != null)
            {
                return View(new SongViewModels
                {
                    Song = obj,
                    Grammar = obj.Grammar,
                    SongId = id
                });
            }
            else
            {
                return Redirect(Url.Action("Error", "Home"));
            }
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditGrammar(SongViewModels model)
        {
            try
            {
                HelloMinasan.Domain.Song songObject = songService.Get(model.SongId);
                if (songObject == null)
                {
                    songObject = new HelloMinasan.Domain.Song
                    {
                        //SongId = model.SongId,
                        Grammar = model.Grammar
                    };
                }

                songService.EditGrammar(songObject);
                return Redirect(Url.Action("Songs", "Song", new { id = model.SongId }));
            }
            catch
            {
                return Redirect(Url.Action("Error", "Home"));
            }
        }

        //[HttpGet]
        //public ActionResult EditSongFiles(int id)
        //{
        //    var obj = new SongRepository().GetSongContent(id);
        //    return View(new SongViewModels
        //    {
        //        Song = obj,
        //        SongId = obj.SongId
        //    });
        //}

        //[HttpPost]
        //public ActionResult EditSongFiles(SongViewModels model)
        //{
        //    //MvcApplication.DBForTest.EditGrammar(model);
        //    return Redirect(Url.Action("Songs", "Song", new { id = model.Song.Id }));
        //}
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddFavouriteSong(int songId)
        {
            var obj = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    songService.AddFavouriteSong(songId, CurrentUser.Id);
                    obj.Result = true;
                    obj.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    obj.Result = false;
                    obj.Message = ex.Message;
                }
            }
            else
            {
                obj.Result = false;
                obj.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(obj);
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult UnAddFavouriteSongs(int songId)
        {
            var obj = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    songService.DeleteFavouriteSong(songId, CurrentUser.Id);
                    obj.Result = true;
                    obj.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    obj.Result = false;
                    obj.Message = ex.Message;
                }
            }
            else
            {
                obj.Result = false;
                obj.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(obj);
        }

        //[HttpGet]
        //public ActionResult AddLyric(int id)
        //{
        //    return View(new LyricViewModel { SongId = id, Lyric = string.Empty });
        //}

        //[HttpPost]
        //public ActionResult AddLyric(LyricViewModel model)
        //{
        //    LyricDetail lyric = new LyricDetail()
        //    {
        //        LanguageId = model.LanguageId,
        //        LyricContent = model.Lyric,
        //        SongId = model.SongId
        //    };
        //    _songIRepository.AddLyric(lyric);
        //    return Redirect(Url.Action("EditLyric", "Song", new { id = model.SongId }));
        //}

        //[HttpGet]
        //public ActionResult EditLyric(int id)
        //{
        //    var objModels = _songIRepository.GetLyricBySongId(id).Where(x => !x.LyricStatus);
        //    return View(new SongViewModels
        //    {
        //        SongId = id,
        //        Lyrics = objModels.ToList()
        //    });
        //}

        //[HttpPost]
        //public ActionResult EditLyric(SongViewModels model)
        //{
        //    _songIRepository.EditLyric(model.Lyrics);
        //    return View(model);
        //}
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CommunityUpdateLyric(int songId, int languageId, string content)
        {

            ResultObject result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    songService.CommunityUpdateLyric(new LyricDetail()
                    {
                        LyricContent = content,
                        //LanguageId = languageId,
                        //SongId = songId
                        Language = userService.GetLanguage(languageId),
                        Song = songService.Get(songId),
                    }, CurrentUser.Id);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Result = false;
                result.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(result);
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CommunityUpdateEmbedLink(int songId, string content)
        {
            ResultObject result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    HelloMinasan.Domain.Song song = songService.Get(songId);
                    if (song == null)
                    {
                        song = new HelloMinasan.Domain.Song()
                        {
                            SongURL = HttpUtility.UrlDecode(content)//,
                            //SongId = songId
                        };
                    }

                    songService.CommunityUpdateEmbedLink(song, CurrentUser.Id);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Result = false;
                result.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(result);
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CommunityLanguageList(int songId)
        {
            var result = new ResultObject();
            try
            {
                var returnedObject = songService.GetLanguage(false, songId);
                var avoidCircleDeserilize = new List<object>();
                returnedObject.ToList().ForEach((x) =>
                {
                    avoidCircleDeserilize.Add(
                        new LanguageObject
                        {
                            LanguageId = x.Id,
                            LanguageName = x.Name
                        });
                });
                result.Result = true;
                result.ReturnObject = avoidCircleDeserilize;
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }
            return Json(result);
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CommunityAddMoreLyric(int songId, int languageId, string content)
        {
            var result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    //var user = _userIRepository.FindUserById(User.Identity.Name);
                    var user = userService.Get(CurrentUser.Id);
                    if (user == null)
                    {
                        throw new Exception(Resource.Song_AddError);
                    }
                    LyricDetail lyric = new LyricDetail()
                    {
                        //LanguageId = languageId,
                        //SongId = songId,
                        Language = userService.GetLanguage(languageId),
                        Song = songService.Get(songId),
                        LyricContent = content.Trim(),
                        //UpdateUser = user.Id,
                        User = user,
                        LastUpdate = DateTime.Now,
                        CanUpdate = true,
                        LyricStatus = false
                    };
                    songService.CommunityAddMoreLyric(lyric);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Message = Resource.Song_RequiredAuthentication;
                result.Result = false;
            }
            return Json(result);
        }
        [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CommunityEditGrammar(int songId, string content)
        {
            var result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    HelloMinasan.Domain.Song song = songService.Get(songId);

                    if (song == null)
                    {
                        song = new HelloMinasan.Domain.Song()
                        {
                            //SongId = songId,
                            Grammar = content
                        };
                    }
                    songService.CommunityGrammar(song);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Message = Resource.Song_RequiredAuthentication;
                result.Result = false;
            }
            return Json(result);
        }
        [Authorize]
        [HttpGet]
        public ActionResult EditTest(int id, int? testId)
        {
            TestEntrie entry;
            if (testId != null && testId > 0)
            {
                entry = new TestEntrie();
                var song = songService.GetSongContent(id);
                entry.Questions = new JavaScriptSerializer().
                        Deserialize<List<Question>>(song.QuestionQuizs.Where(x => x.Id == testId.Value).First().QuizContent);
                ViewBag.ButtonName = "Update";
                entry.SongId = id;
                entry.IsSelectionBlock = true;
            }
            else
            {
                ViewBag.ButtonName = "Select";
                entry = new TestEntrie() { SongId = id };

            }
            return PartialView(entry);
        }
        [Authorize]
        [HttpPost]
        public ActionResult EditTest(TestEntrie entry, string submitButton)
        {
            try
            {
                if (submitButton == "Select")
                {
                    entry.Questions = new List<Question>();
                    for (int i = 0; i < int.Parse(entry.SelectedPackage); i++)
                    {
                        entry.Questions.Add(new Question());
                    }
                    ViewBag.ButtonName = "Submit";
                    entry.IsSelectionBlock = true;
                }
                else if (submitButton == "Update")
                {
                    if (ModelState.IsValid && entry.TestId > 0)
                    {
                        var obj = new JavaScriptSerializer().Serialize(entry.Questions);
                        var quiz = new QuestionQuiz()
                        {
                            PostedDate = DateTime.Now,
                            QuizContent = obj,
                            SongId = entry.SongId//,
                            //Id = entry.TestId not it is auto
                        };
                        songService.UpdateTestQuiz(quiz);
                        return Redirect(Url.Action("TestList", "Song", new { id = entry.SongId }));
                    }
                }
                else
                {
                    ViewBag.ButtonName = "Submit";
                    entry.IsSelectionBlock = true;
                    if (ModelState.IsValid)
                    {
                        var obj = new JavaScriptSerializer().Serialize(entry.Questions);
                        var quiz = new QuestionQuiz()
                        {
                            PostedDate = DateTime.Now,
                            QuizContent = obj,
                            SongId = entry.SongId
                        };
                        songService.AddTestQuiz(quiz);
                        return Redirect(Url.Action("TestList", "Song", new { id = entry.SongId }));
                    }
                }
            }
            catch
            {
                return View();
            }
            return PartialView(entry);
        }
        [Authorize]
        [HttpGet]
        public ActionResult EditBlank(int id, int? testId)
        {
            var model = createBlankTestEntrie(id);
            if (testId != null && testId > 0)
            {
                model.TestId = testId.Value;
            }
            return PartialView(model);
        }

        private BlankTestEntrie createBlankTestEntrie(int songId)
        {
            var song = songService.GetSongContent(songId);
            if (song != null)
            {
                var orginalLyric = song.LyricDetails.Where(x => x.IsOrginal == true).FirstOrDefault();
                string strLyric = orginalLyric.LyricContent;
                //Process data
                orginalLyric.LyricContent = orginalLyric.LyricContent.Trim();
                //Bellow 6 lines will be changed to contants later.
                strLyric = strLyric.Replace(Environment.NewLine, " <br> ");
                strLyric = strLyric.Replace("\n", " <br> ");
                strLyric = strLyric.Replace(".", " . ");
                strLyric = strLyric.Replace(",", " , ");
                strLyric = strLyric.Replace("!", " ! ");
                strLyric = strLyric.Replace("?", " ? ");

                while (strLyric.Contains("  "))
                {
                    strLyric = strLyric.Replace("  ", " ");
                }

                if (orginalLyric != null)
                {
                    var model = new BlankTestEntrie()
                    {
                        ProcessedLyric = strLyric.Split(' ').ToList(),
                        SongId = songId,
                        Positions = new List<int>(),
                        TypeBlank = new List<bool>()
                    };
                    model.Song = song;
                    return model;
                }
            }
            return null;
        }
        [Authorize]
        [HttpPost]
        public ActionResult EditBlank(int testId, int songId, string positions)
        {
            ResultObject result = new ResultObject();
            try
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                List<string> list = ser.Deserialize<string[]>(positions).ToList();
                List<int> selectedPosition = new List<int>();
                List<bool> selectedType = new List<bool>();
                foreach (var item in list)
                {
                    string[] splittedString = item.Split('#');
                    selectedPosition.Add(int.Parse(splittedString[0]));
                    bool type = splittedString[1] == "Easy" ? true : false;
                    selectedType.Add(type);
                }
                var blankTest = createBlankTestEntrie(songId);

                blankTest.Positions = selectedPosition;
                blankTest.TypeBlank = selectedType;
                blankTest.Song = null;
                var serilizaedObject = ser.Serialize(blankTest);
                QuestionBlank question = new QuestionBlank();
                question.PostedDate = DateTime.Now;
                //question.SongId = songId;
                question.Song = songService.Get(songId);
                question.BlankContent = serilizaedObject;
                if (testId != null && testId > 0)
                {
                    //question.Id = testId; //tu delete as ID is not auto created
                    songService.UpdateTestBlank(question);
                }
                else
                    songService.AddTestBlank(question);

                result.Message = Url.Action("TestList", "Song", new { id = songId });
                result.Result = true;
            }
            catch
            {
                result.Message = Resource.Song_AddError;
                result.Result = false;
            }
            return Json(result);
        }
        [HttpGet]
        public ActionResult DoBlankTest(int id)
        {
            BlankTestEntrie model = getBlankTest(id);
            return PartialView(model);
        }
        private BlankTestEntrie getBlankTest(int id)
        {
            bool mode = Request.QueryString["mode"].ToString() == "Easy" ? true : false;
            BlankTestEntrie model = new BlankTestEntrie();
            var song = songService.GetSongContent(id);
            if (song.QuestionBlanks.Any())
            {
                model = new JavaScriptSerializer().Deserialize<BlankTestEntrie>(song.QuestionBlanks.Where(x => x.Id == int.Parse(Request.QueryString["testId"])).First().BlankContent);
                model.Song = song;
                model.Answer = new List<string>();
                foreach (var item in model.Positions)
                {
                    model.Answer.Add(string.Empty);
                }
                model.Mode = mode;
            }
            return model;
        }

        [HttpPost]
        public ActionResult DoBlankTest(BlankTestEntrie model)
        {
            BlankTestEntrie orginalObject = getBlankTest(model.SongId);
            int score = 0;
            int totalQuestion = orginalObject.Positions
                .Where(x => orginalObject.TypeBlank[orginalObject.Positions.IndexOf(x)] == orginalObject.Mode).Count();
            int correctQuestion = 0;
            for (int i = 0; i < orginalObject.Positions.Count; i++)
            {
                if (orginalObject.ProcessedLyric[orginalObject.Positions[i]] == model.Answer[i])
                {
                    correctQuestion++;
                    if (orginalObject.TypeBlank[i])
                        score++;
                    else
                        score += 2;
                }
            }
            if(Request.IsAuthenticated) songService.UpdateScore(CurrentUser.Id, score);
            orginalObject.Answer = model.Answer;
            int correctPercent = totalQuestion > 0 ? correctQuestion * 100 / totalQuestion : 0;
            orginalObject.Result = new TestResult()
            {
                Score = score,
                Total = totalQuestion,
                Correct = correctQuestion,
                CorrectPercent = correctPercent
            };
            return PartialView(orginalObject);
        }

        [HttpGet]
        public ActionResult TestList(int id)
        {
            var song = songService.GetSongContent(id);
            //TO DO here
            TestListViewModel model = new TestListViewModel()
            {
                Blanks = song.QuestionBlanks.ToList(),
                Quizs = song.QuestionQuizs.ToList(),
                Owner = song.User.Id,
                SongId = song.Id
            };
            foreach (var item in model.Blanks) { item.BlankContent = null; }
            foreach (var item in model.Quizs) { item.QuizContent = null; }
            return PartialView(model);
        }
        [Authorize]
        [HttpPost]
        public ActionResult LikeSong(int songId)
        {
            ResultObject result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    songService.LikeSong(CurrentUser.Id, songId);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Result = false;
                result.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(result);
        }

        [Authorize]
        [HttpPost]
        public ActionResult DeleteTest(int testId, bool typeAction)
        {
            ResultObject result = new ResultObject();
            if (Request.IsAuthenticated)
            {
                try
                {
                    songService.DeleteTest(testId, typeAction);
                    result.Result = true;
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                catch (Exception ex)
                {
                    result.Result = false;
                    result.Message = ex.Message;
                }
            }
            else
            {
                result.Result = false;
                result.Message = Resource.Song_RequiredAuthentication;
            }
            return Json(result);
        }

        [Authorize]
        public ActionResult ReportLyric(int lyricId, int songId)
        {
            ResultObject result = new ResultObject();
            result.Result = false;

            if (Request.IsAuthenticated)
            {
                var lyric =
                    songService.GetSongContent(songId)
                    .LyricDetails.Where(x => x.Id == lyricId)
                    .FirstOrDefault();

                if (lyric != null)
                {
                    result.Result = true;
                    //new SongReportRepository().AddReport(new SongReport()
                    //{
                    //    ReportDate = DateTime.Now,
                    //    ReportType = "2",
                    //    SongID = lyric.SongId,
                    //    UserReport = CurrentUser.Id,
                    //    ReportStatus = true,
                    //    LyricID = lyric.ID
                    //});
                    songService.AddReport(new SongReport()
                    {
                        ReportDate = DateTime.Now,
                        ReportType = "2",
                        SongID = lyric.Song.Id,
                        //UserReport = CurrentUser.Id,
                        User = userService.Get(CurrentUser.Id),
                        ReportStatus = true,
                        LyricID = lyric.Id
                    });
                    result.Message = Resource.Song_SuccessfullyEvent;
                }
                else
                {
                    result.Message = "Data is not existed";
                }
            }
            else
            {
                result.Message = Resource.Song_RequiredAuthentication;
            }

            return Json(result);
        }
    }
}
